package com.beta.restapi.controller.upload;

import com.beta.entity.Assets;
import com.beta.service.IAssetsService;
import com.beta.support.ResourceImagePathBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by vector on 2017/1/5.
 */
@Component
public class ProductItemPosterImageHandler extends AbstractImageHandler implements IImageHandler {

    @Autowired
    private IAssetsService assetsService;

    @Override
    public boolean supportType(String pictureType) {
        return "product_item_poster".equals(pictureType);
    }

    @Override
    public String buildRelativePathForSave(HttpServletRequest request, Integer userId, String fileName) {
        Integer productItemId = getProductItemId(request);
        Assets assets = assetsService.createProductItemPosterImage(productItemId, fileName);
        return ResourceImagePathBuilder.assetImagePath(assets.getId(), fileName);
    }

    @Override
    protected String buildImageRelativePathForDelete(HttpServletRequest request, Integer userId) {
        Assets posterImage = assetsService.getProductItemPosterImage(getProductItemId(request));
        if (Objects.isNull(posterImage)) {
            return null;
        }
        return posterImage.getAttachmentUrl();
    }

    @Override
    public void afterImageSave(HttpServletRequest request, Integer userId, String fileName) {
        return ;
    }

    @Override
    protected void afterImageDelete(HttpServletRequest request, Integer userId) {
        super.afterImageDelete(request, userId);
        assetsService.deleteProductItemPosterImage(getProductItemId(request));
    }

    private Integer getProductItemId(HttpServletRequest request) {
        return Integer.parseInt(request.getParameter("product_item_id"));
    }

}
